package com.may._4;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 实现一个自旋锁（利用CAS）
 *
 * 创建A、B两个线程，A线程先获取到锁，持有5秒，期间B线程不断循环尝试获取锁，直到A线程释放锁。
 */
public class SpinLockDemo {
    //原子引用线程
    AtomicReference<Thread> reference = new AtomicReference<>();

    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"\t 我来了...");
        while (!reference.compareAndSet(null,thread)){

        }
    }

    public void myUnlock(){
        Thread thread = Thread.currentThread();
        reference.compareAndSet(thread,null );
        System.out.println(thread.getName()+"\t 我走了...");
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(() -> {
            spinLockDemo.myLock();
            try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}
            spinLockDemo.myUnlock();
        },"A").start();

       try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}

        new Thread(() -> {
            spinLockDemo.myLock();
            try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            spinLockDemo.myUnlock();
        },"B").start();
    }
}
